﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Diagnostics;

namespace Pingy.Commanding
{
    public class DelegateCommand<T> : ICommand
    {
        private readonly Func<T, bool> _canExecute;
        private readonly Action<T> _execute;

        public event EventHandler CanExecuteChanged;

        public DelegateCommand(Action<T> execute)
            : this(execute, null)
        {
        }

        public DelegateCommand(Action<T> execute, Func<T, bool> canExecute)
        {
            if (execute == null)
            {
                throw new ArgumentNullException("execute", "Command must have an execute action");
            }

            _execute = execute;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            if (_canExecute == null)
            {
                return true;
            }

            if (parameter is T)
            {
                return _canExecute((T)parameter);
            }
            else
            {
                throw new ArgumentException(string.Format("Parameter '{0}' was not of type {1}", parameter, typeof(T)));
            }
        }

        public void Execute(object parameter)
        {
            if (parameter is T)
            {
                _execute((T)parameter);
            }
            else
            {
                throw new ArgumentException(string.Format("Parameter '{0}' was not of type {1}", parameter, typeof(T)));
            }
        }

        public void RaiseCanExecuteChanged()
        {
            if (CanExecuteChanged != null)
            {
                CanExecuteChanged(this, EventArgs.Empty);
            }
        }
    }
}
